package com.example.ivideo_2211a.fg

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.example.common.mvi.BaseViewFragment
import com.example.common.room.VideoDatabase
import com.example.common.room.VideoRepository
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.adapter.HistoryVideoAdapter
import com.example.ivideo_2211a.databinding.FragmentMineBinding
import com.example.ivideo_2211a.home.HomeData
import com.example.ivideo_2211a.utils.LiveBroadcastUtils
import com.google.gson.Gson
import kotlinx.coroutines.launch

class MineFragment : BaseViewFragment<FragmentMineBinding>() {

    companion object {
        private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1002
        private const val TAG = "MineFragment"
    }

    private lateinit var videoRepository: VideoRepository
    private lateinit var historyAdapter: HistoryVideoAdapter

    override fun getLayoutId(): Int {
        return R.layout.fragment_mine
    }

    override fun setupViews() {
        // 初始化数据库
        initDatabase()
        
        // 初始化RecyclerView
        initHistoryRecyclerView()
        
        // 加载点赞视频数据
        loadLikedVideos()
        
        // 点击个人中心进入登录注册页面
        binding.personalPage.setOnClickListener {
            ARouter.getInstance().build("/user/LoginActivity").navigation()
        }
        binding.myFavorites.setOnClickListener {
            ARouter.getInstance().build("/collection/CollectionActivity").navigation()
        }
        
        // 点击开直播按钮
        binding.startLive.setOnClickListener {
            // 检查通知权限并发送广播
            checkNotificationPermissionAndSendBroadcast()
            // 跳转到直播页面
            ARouter.getInstance().build("/app/StartLiveActivity").navigation()
        }
        
        val i = SPUtils.getInstance().getInt("coin_count")
        binding.coinAmount.text="$i"
    }
    
    /**
     * 检查通知权限并发送广播
     */
    private fun checkNotificationPermissionAndSendBroadcast() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS) 
                != PackageManager.PERMISSION_GRANTED) {
                // 请求通知权限
                ActivityCompat.requestPermissions(requireActivity(), 
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS), 
                    NOTIFICATION_PERMISSION_REQUEST_CODE)
            } else {
                // 已有权限，直接发送广播
                sendLiveNotification()
            }
        } else {
            // Android 13以下版本不需要运行时权限
            sendLiveNotification()
        }
    }
    
    /**
     * 发送直播通知
     */
    private fun sendLiveNotification() {
        LiveBroadcastUtils.sendLiveStartNotification(requireContext(), "用户即将开始直播")
        Log.d(TAG, "已发送直播预播提醒广播")
    }
    
    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            NOTIFICATION_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "通知权限已授权")
                    // 权限授权后发送通知
                    sendLiveNotification()
                } else {
                    Log.w(TAG, "通知权限被拒绝，无法显示通知")
                    // 即使权限被拒绝，也尝试发送广播（某些设备可能仍能显示）
                    sendLiveNotification()
                }
            }
        }
    }
    
    private fun initDatabase() {
        val database = VideoDatabase.getDatabase(requireContext())
        videoRepository = VideoRepository(database.videoFavoriteDao())
    }
    
    private fun initHistoryRecyclerView() {
        historyAdapter = HistoryVideoAdapter { videoFavorite ->
            // 点击历史视频项，跳转到播放页面
            val homeData = HomeData(
                id = videoFavorite.id,
                title = videoFavorite.title,
                videopath = videoFavorite.videopath,
                avatar_url = videoFavorite.avatar_url,
                name = videoFavorite.name,
                videomainimag = "", // VideoFavorite中没有这个字段，使用空字符串
                playnum = 0, // VideoFavorite中没有这个字段，使用0
                channelid = "",
                commentnum = 0,
                ctime = "",
                description = "",
                group_id = "",
                image_url = "",
                labelIds = "",
                preview_url = "",
                publish_time = "",
                userid = "",
                verifycode = "",
                item_id = "",
            )
            val videoDataJson = Gson().toJson(homeData)
            ARouter.getInstance()
                .build("/playvideo/PlayVideoActivity")
                .withString("videoDataJson", videoDataJson)
                .navigation()
        }
        
        binding.historyRecyclerView.apply {
            adapter = historyAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        }
    }
    
    private fun loadLikedVideos() {
        lifecycleScope.launch {
            try {
                // 获取所有点赞的视频
                videoRepository.getAllLikedVideos().collect { likedVideos ->
                    // 更新RecyclerView数据
                    historyAdapter.submitList(likedVideos)
                    
                    // 如果没有数据，可以显示空状态
                    if (likedVideos.isEmpty()) {
                        // 这里可以显示空状态提示
                        println("暂无观看历史")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                println("加载观看历史失败: ${e.message}")
            }
        }
    }
}